const log = require('./log'),
    logger = require('log4js').getLogger();

exports.handlePost = (req, res, resolve) => {
    var method = req.method;
    if (method != 'POST') {
        res.writeHead(500, {
            "Content-Type": "text/html"
        })
        res.end("<h1>500 Error</h1>")
        return
    }
    var body = []
    req.on('error', (err) => {
        log(err)
        res.writeHead(500, {
            "Content-Type": "text/html"
        });
        res.end("<h1>500 Error</h1>")
    }).on('data', function (chunk) {
        body.push(chunk)
    }).on('end', function () {
        var repStr = Buffer.concat(body).toString();
        try {
            resolve(JSON.parse(repStr), respJSON => {
                res.statusCode = 200;
                res.setHeader('Content-Type', 'text/json')
                res.end(JSON.stringify(respJSON))
            })
        } catch (err) {
            logger.error('[' + __filename + ':' + __line + ']', err)
            logger.error('[' + __filename + ':' + __line + ']', repStr.length > 100 ? (repStr.substring(0, 100) + '...') : repStr)
            res.writeHead(500, {
                "Content-Type": "text/html"
            })
            res.end("<h1>500 Error</h1>")
        }
    })
}

exports.handleGet = (req, res, resolve) => {
    var method = req.method;
    if (method != 'GET') {
        res.writeHead(500, {
            "Content-Type": "text/html"
        });
        res.end("<h1>500 Error</h1>")
        return
    }
    var reqObj = {};
    req.url.split('?')[1] && req.url.split('?')[1].split('&').forEach(item => {
        reqObj[item.split('=')[0]] = item.split('=')[1]
    })
    resolve(reqObj, respJSON => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/json')
        res.end(JSON.stringify(respJSON))
    })
}

exports.handleBusPost = (req, res, resolve) => {
    res.writeHead(200, {
        'Content-Type': 'text/json'
    })
    if (req.method != 'POST') {
        log('只能post')
        res.end(JSON.stringify({
            result: -1,
            msg: '只能post'
        }))
        return
    }
    var body = []
    req.on('error', err => {
        log(err)
        res.end(JSON.stringify({
            result: -1,
            msg: '系统错误'
        }))
    }).on('data', chunk => {
        body.push(chunk)
    }).on('end', () => {
        var reqStr = Buffer.concat(body).toString();
        try {
            var reqObj = JSON.parse(reqStr)
            if (!reqObj.uuid) {
                log('缺少uuid')
                res.end(JSON.stringify({
                    result: -1,
                    msg: '缺少uuid'
                }))
                return
            }
            resolve(reqObj)
        } catch (err) {
            log(err)
            res.end(JSON.stringify({
                result: -1,
                msg: '不是json'
            }))
        }
    })
}

exports.createHttpServer = obj => {
    obj = obj || {}
    var svc = obj.svc || []
    var root = obj.root || __dirname
    var port = obj.port || 80
    require('http').createServer((req, res) => {
        require('../mng/sessionMng').get(req, res)
        var uri = req.url
        if (uri.lastIndexOf('.do') != -1) {
            var svcn = uri.substring(uri.lastIndexOf('/') + 1, uri.lastIndexOf('.do')); // short for service name
            if (svc[svcn]) {
                if (svc[svcn].needLogin) {
                    if (!req.session.user) {
                        res.statusCode = 200;
                        res.setHeader('Content-Type', 'text/json')
                        res.end(JSON.stringify({
                            result: 0
                        }))
                        return
                    }
                    if (svc[svcn].allowUsers && svc[svcn].allowUsers.indexOf(req.session.user.id) == -1) {
                        res.statusCode = 200;
                        res.setHeader('Content-Type', 'text/json')
                        res.end(JSON.stringify({
                            result: -1
                        }))
                        return
                    }
                } else if (svc[svcn].needCustomerLogin) {
                    if (!req.session.customer) {
                        res.statusCode = 200;
                        res.setHeader('Content-Type', 'text/json')
                        res.end(JSON.stringify({
                            result: 0
                        }))
                        return
                    }
                } else if (svc[svcn].needAdminLogin) {
                    if (!req.session.admin) {
                        res.statusCode = 200;
                        res.setHeader('Content-Type', 'text/json')
                        res.end(JSON.stringify({
                            result: 0
                        }))
                        return
                    }
                }
                svc[svcn].serve(req, res);
                return
            } else {
                logger.debug('[' + __filename + ':' + __line + '] ' + svcn + '服务不存在')
            }
        }
        var pathname = root
        try {
            pathname += decodeURIComponent(url.parse(uri).pathname);
        } catch (err) {
            logger.error('[' + __filename + ':' + __line + ']', err, uri)
            res.writeHead(404, {
                'Content-Type': 'text/html'
            })
            res.end('<h1>404 Not Found</h1>')
            return
        }
        if (path.extname(pathname) == '') {
            pathname += "/";
        }
        if (pathname.charAt(pathname.length - 1) == "/") {
            pathname += 'index.html';
        }
        require('fs').exists(pathname, (exists) => {
            if (exists) {
                switch (path.extname(pathname).toLowerCase()) {
                    case '.html':
                        res.writeHead(200, {
                            'Content-Type': 'text/html'
                        });
                        break;
                    case '.js':
                        res.writeHead(200, {
                            'Content-Type': 'text/javascript'
                        });
                        break;
                    case '.css':
                        res.writeHead(200, {
                            'Content-Type': 'text/css'
                        });
                        break;
                    case '.gif':
                        res.writeHead(200, {
                            'Content-Type': 'image/gif'
                        });
                        break;
                    case '.jpg':
                        res.writeHead(200, {
                            'Content-Type': 'image/jpeg'
                        });
                        break;
                    case '.png':
                        res.writeHead(200, {
                            'Content-Type': 'image/png'
                        });
                        break;
                    case '.mp3':
                        res.writeHead(200, {
                            'Content-Type': 'video/mp3'
                        });
                        break;
                    case '.mp4':
                        res.writeHead(200, {
                            'Content-Type': 'video/mp4'
                        });
                        break;
                    default:
                        res.writeHead(200, {
                            'Content-Type': 'application/octet-stream'
                        });
                }
                var rs = require('fs').createReadStream(pathname)
                rs.on('end', () => {
                    res.end()
                })
                rs.pipe(res)
                return
            }
            // log(uri + '不存在')
            res.writeHead(404, {
                'Content-Type': 'text/html'
            })
            res.end('<h1>404 Not Found</h1>')
        })
    }).listen(port, () => {
        logger.debug('[' + __filename + ':' + __line + ']', 'http listening ' + port)
    })
}